package cn.powertime.evaluation.idempotent;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 *     处理幂等性注解的HandlerInterceptor。也可以使用AOP实现
 * </p>
 * @author ZYW
 * @version 1.0
 * @date 2019-08-19 21:18
 */
public class ApiIdempotentInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod)handler;
        ApiIdempotent methodAnnotation = handlerMethod.getMethodAnnotation(ApiIdempotent.class);
        if(methodAnnotation != null) {
            check(request); // 幂等性校验, 校验通过则放行, 校验失败则抛出异常, 并通过统一异常处理返回友好提示
        }

        return true;
    }

    private void check( HttpServletRequest request) {
        tokenService.checkToken(request);
    }
}
